<!-- 代码已包含 CSS：使用 TailwindCSS , 安装 TailwindCSS 后方可看到布局样式效果 -->

<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="bg-white rounded-lg shadow-lg flex min-h-[600px]">
      <!-- 左侧产品列表 -->

      <div class="w-[400px] border-r border-gray-200 flex flex-col">
        <div class="relative mb-4">
          <el-input
            v-noSpace
            v-model="queryParams.productName"
            @keyup.enter="getProductList"
            placeholder="搜索产品"
            class="!rounded-lg"
          />
        </div>
        <div class="flex-1 overflow-y-auto">
          <div
            v-for="product in productTableData"
            :key="product.code"
            @click="handleProductSelect(product)"
            :class="{
              'bg-blue-50': selectedProduct?.code === product.code,
              'hover:bg-gray-50': selectedProduct?.code !== product.code,
            }"
            class="px-4 py-3 cursor-pointer transition-colors"
          >
            <div class="truncate flex justify-between text-gray-700">
              <div>
                {{ product.productName }}
              </div>
              <div>
                {{ product.price }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧图表区域 -->
      <div class="flex-1 p-6">
        <div v-if="selectedProduct">
          <div class="mb-6">
            <h2 class="text-xl font-medium text-gray-900">
              {{ selectedProduct.productName }} - 价格趋势
              <el-button
                v-hasPerm="'sys:productPrice:edit'"
                @click="addPrice({}, 'add')"
                type="primary"
              >
                新增价格
              </el-button>
            </h2>
            <div class="mt-2 flex items-center space-x-4 text-sm text-gray-500">
              <span>最高价: ¥{{ maxPrice }}</span>
              <span>最低价: ¥{{ minPrice }}</span>
              <span>价格变化: {{ priceChange }}%</span>
            </div>
          </div>

          <div class="mb-4 space-x-2">
            <el-button
              v-for="period in periods"
              :key="period.value"
              :type="currentPeriod === period.value ? 'primary' : 'default'"
              @click="handlePeriodChange(period.value)"
              class="!rounded-button whitespace-nowrap"
            >
              {{ period.label }}
            </el-button>
          </div>

          <div class="echartsClass">
            <ECharts @chart-click="handleChartClick" :options="chartOptions" />
          </div>
        </div>

        <div v-else>
          <div class="h-full flex items-center justify-center text-gray-400">
            请选择左侧产品查看价格趋势
          </div>
        </div>
      </div>
    </div>
    <div class="bg-white shadow-lg">
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getProductList"
      />
    </div>
    <el-dialog
      v-model="dialogVisible.visible"
      :title="dialogVisible.title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        ref="dialogFormRef"
        :disabled="dialogVisible.type == 'info' ? true : false"
        :model="dialogFormData"
        v-loading="loading"
        :rules="rules"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item label="价格" prop="amount">
              <el-input v-noSpace v-model="dialogFormData.amount" placeholder="请输入价格" />
            </el-form-item>
          </el-col>
          <el-col :span="24" class="text-align-right">
            <span class="dialog-footer df">
              <el-button v-debounce="subPrice" type="primary">提 交</el-button>
            </span>
          </el-col>
        </el-row>
      </el-form>
      <!-- <template #footer>
        <span class="dialog-footer df">
          <el-button type="primary">确 定</el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import type { EChartsOption } from "echarts";
import * as echarts from "echarts";
import productBomAPI from "@/api/productBom/productBom";
import { FormItemRule } from "element-plus/es";
import productPrice from "@/api/priceMaintenance/productPrice";
import { useDateRanges } from "@/utils/useDateRanges";
import { tableRowFormatter, validatePositiveInteger } from "@/utils/index";
// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 时间范围
const { getWeekRange, getMonthRange, getQuarterRange, getYearRange, getDateRange } =
  useDateRanges();
const weekRange = ref(getWeekRange());
const monthRange = ref(getMonthRange());
const quarterRange = ref(getQuarterRange());
const yearRange = ref(getYearRange());
// 一级弹窗ref
const dialogFormRef = ref(ElForm);
//一级弹窗
const dialogVisible = reactive({ visible: false, title: "", type: "" });
//一级表单验证
const rules = reactive<Record<string, FormItemRule[]>>({
  amount: [{ required: true, validator: validatePositiveInteger, trigger: "blur" }],
  // type: [{ required: true, message: "请输入类型", trigger: "blur" }],
});
const dialogFormData: {
  id?: string;
  //金额
  amount?: string;
  amountTime?: string;
  productCode?: string;
} = reactive({});
// 产品价格查询参数
interface priceQuery {
  /** 时间范围数组 */
  timeScopes?: string[];
  // 产品code
  productCode?: string;
}
const priceParams: priceQuery = reactive({
  // timeScopes:[]
});
// 产品列表查询参数
interface seachQuery extends PageQuery {
  //产品类型
  productType?: number;
  productName?: string;
}
const queryParams: seachQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  productType: 1,
  productName: "",
});

const chartOptions: EChartsOption = reactive({});
const chartRef = ref<HTMLElement | null>(null);
const chart = ref<echarts.ECharts | null>(null);
const currentPeriod = ref("month");

const periods = [
  { label: "周", value: "week", timeScopes: [weekRange.value.start, weekRange.value.end] },
  { label: "月", value: "month", timeScopes: [monthRange.value.start, monthRange.value.end] },
  {
    label: "季度",
    value: "quarter",
    timeScopes: [quarterRange.value.start, quarterRange.value.end],
  },
  { label: "年", value: "year", timeScopes: [yearRange.value.start, yearRange.value.end] },
];
const periodsFormat = () => {
  return periods.find((item) => item.value === currentPeriod.value)?.timeScopes;
};
console.log(periods, "periods");

const maxPrice = ref(0);
const minPrice = ref(0);
const priceChange = ref(0);

const updateChart = () => {
  if (productpriceTableList.value.length == 0) {
    maxPrice.value = 0;
    minPrice.value = 0;
    priceChange.value = 0;
  } else {
    const prices = productpriceTableList.value.map((item: any) => Number(item.amount));
    maxPrice.value = Math.max(...prices) || 0;
    minPrice.value = Math.min(...prices);
    priceChange.value = Number(
      (((prices[prices.length - 1] - prices[0]) / prices[0]) * 100).toFixed(2)
    );
  }

  const option: EChartsOption = {
    animation: false,
    tooltip: {
      trigger: "axis",
      formatter: (params: any) => {
        const data = params[0];
        return `${data.name}<br/>价格: ¥${data.value}`;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: productpriceTableList.value.map((item: any) => item.amountTime),
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "¥{value}",
      },
    },
    series: [
      {
        name: "价格",
        type: "line",
        data: productpriceTableList.value.map((item: any) => item.amount),
        smooth: true,
        lineStyle: {
          width: 3,
        },
        symbol: "circle", // 设置原点形状
        symbolSize: 10, // 设置原点大小
        itemStyle: {
          color: "#3b82f6",
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: "rgba(59,130,246,0.3)",
            },
            {
              offset: 1,
              color: "rgba(59,130,246,0.1)",
            },
          ]),
        },
      },
    ],
  };
  Object.assign(chartOptions, { ...option });
  // chart.value.setOption(option);
};
// 产品列表点击
const handleProductSelect = (product: any) => {
  selectedProduct.value = product;
  console.log(product);
  priceParams.timeScopes = periodsFormat();
  priceParams.productCode = product.code;
  getPriceList();
};
// 时间切换点击
const handlePeriodChange = (period: string) => {
  currentPeriod.value = period;
  priceParams.timeScopes = periodsFormat();
  getPriceList();
};
const selectedProduct = ref<{ code: string; productName: string } | null>(null);
// 产品列表数据
const productTableData = ref<{ code: string; productName: string; price: string }[]>([]);
const getProductList = async (type = false) => {
  try {
    const response = await productBomAPI.getTypePage(queryParams);
    console.log(type, "type");
    total.value = response.total;
    const dataList = response?.list || [];
    productTableData.value = dataList.map((item: any) => ({
      code: item.code ?? "", // 确保有 code 属性
      productName: item.productName ?? "", // 确保有 productName 属性
      price: item.price ?? "", // 确保有 productName 属性
    }));

    if (type) {
      handleProductSelect(selectedProduct.value);
    } else {
      selectedProduct.value = null;
      productpriceTableList.value = [];
    }
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};
const productpriceTableList = ref<
  { productCode: string; amount: string; amountTime: string; id: string }[]
>([]);
// 价格趋势
const getPriceList = () => {
  productPrice
    .getProductPriceList(priceParams)
    .then((data) => {
      console.log(data);
      productpriceTableList.value = [...(data as any)];

      // Object.assign(productpriceTableList.value, { ...data });
      updateChart();
    })
    .finally(() => {
      loading.value = false;
    });
};
// 新增价格
const addPrice = (row: any, type: any) => {
  dialogVisible.visible = true;
  dialogVisible.type = type;
  if (type === "add") {
    dialogVisible.title = "新增价格";
    delete dialogFormData.id;
  }
  if (type === "edit") {
    dialogVisible.title = "修改价格";
    let data = { ...row };
    nextTick(() => {
      Object.assign(dialogFormData, { ...data });
      console.log(dialogFormData, "dialogFormData");
    });
  }
};
// 弹窗关闭
const handleClose = () => {
  dialogVisible.visible = false;
  dialogFormRef.value?.clearValidate();
  dialogFormRef.value?.resetFields();
};
// 保存价格
const subPrice = () => {
  loading.value = true;
  if (dialogVisible.type == "add") {
    dialogFormData.productCode = priceParams.productCode;
    // dialogFormData.amountTime = "2025-01-16";
    dialogFormData.amountTime = getDateRange();
  }

  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }

    productPrice
      .saveOrUpdateProductPrice(dialogFormData)
      .then((data) => {
        loading.value = false;
        dialogVisible.visible = false;
        ElMessage.success("保存成功");
        getProductList(true);

        // getPriceList();
        // handleSeach();
      })
      .catch((error) => {
        loading.value = false;
        // ElMessage.error(`error`);
      });
  });
};
const handleChartClick = (params: any) => {
  console.log("父组件接收到的点击事件数据:", params);
  console.log(productpriceTableList.value[params.dataIndex]);
  addPrice(productpriceTableList.value[params.dataIndex], "edit");
};

onMounted(() => {
  getProductList();
  if (chartRef.value) {
    chart.value = echarts.init(chartRef.value);
  }
});

// watch(selectedProduct, () => {
//   if (selectedProduct.value) {
//     updateChart(currentPeriod.value);
//   }
// });
</script>

<style scoped>
.echartsClass {
  /* width: 400px; */
  height: 400px;
}
.el-button {
  height: 32px;
  padding: 0 16px;
}

::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.3);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.5);
}
</style>
